package servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import by.grsu.hdm.devices.MediaCenter;
import by.grsu.hdm.devices.UsbFlashDrive;
import by.grsu.hdm.exeption.NoReproductionFormatException;
import by.grsu.hdm.media.Track;

/**
 * Servlet implementation class ButtonAction
 */
@WebServlet("/ButtonAction")
public class ButtonAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ButtonAction() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String status = null;
		String button = request.getParameter("button");
		 HttpSession session = request.getSession(true);
		 MediaCenter media=(MediaCenter)session.getAttribute("media");
		Track track=((UsbFlashDrive) media.getUsbPort().getConnectedDevice()).getTracks().get(request.getParameter("track"));
		
		if (track != null) {
			if (button.equals("play")) {
				
				try {
					status = media.getMediaPlayer().getRemoteControl().getButtons().get("start").getAction(media,track);
				} catch (NoReproductionFormatException e) {
					// TODO Auto-generated catch block
					status=e.getMessage();
				}
			}

			if (button.equals("pause")) {
				try {
					status = media.getMediaPlayer().getRemoteControl().getButtons().get("pause").getAction(media,track);
				} catch (NoReproductionFormatException e) {
					// TODO Auto-generated catch block
					status=e.getMessage();
				}
			}
			if (button.equals("stop")) {
				try {
					status = media.getMediaPlayer().getRemoteControl().getButtons().get("stop").getAction(media,track);
				} catch (NoReproductionFormatException e) {
					// TODO Auto-generated catch block
					status=e.getMessage();
				}
			}
		} else
			status = "Please check File";
		request.setAttribute("status", status);
		request.getRequestDispatcher("Status.jsp").forward(request, response);

	}

}
